function query() {
    $.ajax({
        url: basePath + "/department/department/departmentTree",
        type: "get",
        dataType: "json",
        success: function (treeNode) {
            zNodes = treeNode;
            $.fn.zTree.init($("#departmentTree"), setting, zNodes);
            zTree = $.fn.zTree.getZTreeObj("departmentTree");
            var nodes = zTree.getNodes();
            zTree.expandNode(nodes[0], true, false, true);
        },
        error: doError
    });
}


function beforeDrag(treeId, treeNodes) {
    for (var i = 0, l = treeNodes.length; i < l; i++) {
        if (treeNodes[i].drag === false) {
            toast.success("该用户组节点不能进行拖拽操作！");
            return false;
        }
    }
    return true;
}

function beforeDrop(treeId, treeNodes, targetNode, moveType, isCopy) {
    $.ajax({
        url: basePath + "/department/department/dragDepartTree",
        data: {
            treeNodeId: treeNodes[0].id,
            targetNodeId: targetNode.id,
            isCopy: isCopy
        },
        dataType: "json",
        type: "post",
        success: function () {
            toast.success("用户组拖拽操作成功！")
        },
        error: doError
    })
}

function zTreeOnClick() {
    var treeObj = $.fn.zTree.getZTreeObj("departmentTree");
    var nodes = treeObj.getSelectedNodes();
    if (nodes.length > 0) {
        treeObj.expandNode(nodes[0]);
    }
}

function zTreeOnDblClick() {
    if (zTree.getSelectedNodes()[0].level == 0) {
        toast.warning("用户组根节点不能选择用户！");
        return
    }
    toPartManage(zTree.getSelectedNodes()[0].id);
}

function toPartManage(nodeId) {
    $("#iframe").attr("src", basePath + "department/department/changeDepartmentUserDo?nodeId=" + nodeId)
}


$(document).ready(function () {
    key = $("#key");
    key.bind("input", searchNode);

    function searchNode() {
        updateNodes(false);
        if (key.get(0).value != "" && key.get(0).value != " ") {
            nodeList = zTree.getNodesByParamFuzzy("name", $.trim(key.get(0).value));
            updateNodes(true);
        } else {
            updateNodes(false);
            nodeList = zTree.getNodesByFilter(filter);
        }
    }

    function updateNodes(highlight) {
        var zTree = $.fn.zTree.getZTreeObj("departmentTree");
        for (var i = 0, l = nodeList.length; i < l; i++) {
            nodeList[i].highlight = highlight;
            zTree.updateNode(nodeList[i]);
        }
    }

    function filter(node) {
        return !node.isParent && node.isFirstNode;
    }
});

function getFontCss(treeId, treeNode) {
    return (!!treeNode.highlight) ? {color: "#A60000", "font-weight": "bold"} : {color: "#333", "font-weight": "normal"};
}

function addDepartDo() {
    if (zTree.getSelectedNodes() == "") {
        toast.warning("请在用户组树上选择要新增的父节点！");
        return;
    }
    var url = 'department/department/addDepartmentDo?parentNodeId=' + zTree.getSelectedNodes()[0].id ;
    $("#dialogTitle").text("新增用户组");
    $("#departmentTreeIframe").attr("src", basePath + url);
    $("#modalDialog").modal("show");
}

function editDepartDo() {
    if (zTree.getSelectedNodes() == "") {
        toast.warning("请在部门树上选择需要编辑的部门节点！");
        return;
    }
    if (zTree.getSelectedNodes()[0].level == 0) {
        toast.warning("部门根节点不能编辑！");
        return
    }
    var url = 'department/department/editDepartmentDo?departmentId=' + zTree.getSelectedNodes()[0].id;
    $("#dialogTitle").text("编辑用户组");
    $("#departmentTreeIframe").attr("src", basePath + url);
    $("#modalDialog").modal("show");
}

function delDepart() {
    if (zTree.getSelectedNodes() == "") {
        toast.warning("请在部门树上选择需要删除的部门节点！");
        return;
    }
    if (zTree.getSelectedNodes()[0].level == 0) {
        toast.warning("部门根节点不能删除！");
        return;
    }
    if (zTree.getSelectedNodes()[0].isParent) {
        toast.warning("该用户组有子节点不能删除！");
        return;
    }

    $('#deleteRowConfirm').modal('show');
    $("#deleteRow").unbind("click.deleteRow").bind("click.deleteRow", function () {
        $.ajax({
            url: basePath + "department/department/delDepartment?id=" + zTree.getSelectedNodes()[0].id,
            dataType: "json",
            type: "DELETE",
            success: function (data) {
                deleteNode(data)
                $('#deleteRowConfirm').modal('hide');
                toast.success();
            },
            error: doError
        })
    })
}

function deleteNode(count) {
    var nodes = zTree.getSelectedNodes();

    for (var i = 0, l = nodes.length; i < l; i++) {
        zTree.removeNode(nodes[i]);
    }
}

function addNode(newNodeObj) {
    var pidNode = zTree.getSelectedNodes();
    zTree.addNodes(pidNode[0], newNodeObj);
}
function updateNodeName(name) {
    var pidNode = zTree.getSelectedNodes();
    pidNode[0].name = name;
    zTree.updateNode(pidNode[0]);
}

function resizeHeight() {
    var height = document.documentElement.clientHeight - 400;
    $("#departmentTree").height(height);
}

window.onload = window.onresize = resizeHeight;


var rule = {
    objInfo: {
        departmentNo: {
            checkEmpty: ["departmentNo", "部门编号"],
            max: ["departmentNo", 12, "部门编号"]
        },

        departmentName: {
            checkEmpty: ["departmentName", "部门名称"],
            max: ["departmentName", 15, "部门名称"]
        }
    }
}
function backFunc(data, returnObj) {
    returnObj.obj = $('#departmentNo')
    returnObj.errMsg = "部门编号已存在！"
    if (data == "true") {
        returnObj.bool = true;
    }
    if (data == "false") {
        returnObj.bool = false;
    }

    return returnObj;
}
function addSave() {
    var addRule = $.extend(true, {}, rule, {
        objInfo: {
            departmentNo: {
                ajax: [basePath + "department/department/validateDepartmentNo", {}, {departmentNo: "$('#departmentNo').val().trim()"},
                    backFunc, "text", "POST"]
            }
        }
    });
    if (!JC.validate(addRule)) return;
    $("#saves").button('loading');

    $.ajax({
        url: basePath + "department/department/addDepartment?parentNodeId=" + $("#parentId").val(),
        data: {
            departmentNo: $("#departmentNo").val(),
            departmentName: $("#departmentName").val(),
            userIdList: $("#userIds").val()
        },
        type: "POST",
        dataType: "text",
        success: function (data) {
            var nodeObj = {
                id: data,
                name: $("#departmentName").val()
            }
            parent.addNode(nodeObj);
            location.href = "about:blank";
            parent.$("#modalDialog").modal("hide");
        },
        error: doError
    })
}

function editSave() {
    if (!JC.validate(rule)) return;
    $("#saves").button('loading');

    $.ajax({
        url: basePath + 'department/department/editDepartment?oldDepartmentNo='+$("#oldDepartmentNo").val()+'&userIdList='+ $("#userIds").val(),
        data: {
            id: $("#departmentId").val(),
            departmentNo: $("#departmentNo").val(),
            departmentName: $("#departmentName").val()
        },
        dataType: "json",
        type: "POST",
        success: function () {
            location.href = "about:blank";
            parent.$("#modalDialog").modal("hide");
            parent.updateNodeName($("#departmentName").val());
        },
        error: doError
    })
}

function changeSelect(originalSelect, purposeSelect) {
        $("#" + originalSelect + " option:selected").appendTo($("#" + purposeSelect));
        $("#" + purposeSelect + " option").removeAttr("selected");
    }
    function changeSelectAll(originalSelect, purposeSelect) {
        $("#" + originalSelect + " option").attr("selected", "selected");
        $("#" + originalSelect + " option:selected").appendTo($("#" + purposeSelect));
        $("#" + purposeSelect + " option").removeAttr("selected");
    }

    function saveUsers() {
        var departUsersObj = [];
        departUsersObj.push("");
        $("#scope_list").find("option").each(function (i) {
            departUsersObj.push($(this).val())
        });
        $.ajax({
            url: basePath + 'department/department/changeDepartmentUser',
            data: {
                departmentId: $("#departmentId").val(),
                departUsers: departUsersObj
            },
            dataType: "json",
            type: "POST",
            success: function () {
                parent.$("#iframe").attr("src","");
                parent.query();
                parent.toast.success();
            },
            error: doError
        })

    }

function quit() {
    location.href = "about:blank";
    parent.$("#modalDialog").modal("hide");
}